package com.bridgeintelligent.tag.bulkload.service.core;

import com.bridgeintelligent.tag.constants.bulkload.BulkLoadMqMsg;
import com.bridgeintelligent.tag.bulkload.service.core.chain.BaseLoadChainTempleHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by JackCheung on 2019/9/20 5:24 PM.
 */
@Component
public class BulkEventHandler implements IBulkEventHandler, ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;
    private List<BaseLoadChainTempleHandler> loadChainHandlerList = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext,
                                                                                 BaseLoadChainTempleHandler.class);
        for (String beanName : beanNames) {
            loadChainHandlerList.add((BaseLoadChainTempleHandler) applicationContext.getBean(beanName));
        }
    }

    @Override
    public void setApplicationContext(
            @SuppressWarnings("NullableProblems") ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 处理消息
     *
     * @param bulkLoadMqMsg bulkLoadMqMsg
     */
    @Override
    public void handler(BulkLoadMqMsg bulkLoadMqMsg) {
        if (loadChainHandlerList.size() == 0) {
            return;
        }
        for (BaseLoadChainTempleHandler baseLoadChainHandler : loadChainHandlerList) {
            //不同类型的Handler处理不同的消息
            if (baseLoadChainHandler.getMsgType() == bulkLoadMqMsg.getType()) {
                baseLoadChainHandler.loadHandler(bulkLoadMqMsg);
                break;
            }
        }
    }
}
